package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.baidu.location.LocationClient;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.db.DBUtil;
import com.hcinfos.gsoo.enity.Area;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.interaze.OnViewLastListener;
import com.hcinfos.gsoo.json.CityJson;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.CommonUtil;
import com.hcinfos.gsoo.util.DateUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.NetWorkHelper;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.view.MyScrollLayout;

/**
 * 第一次欢迎页面
 * 
 * @author john
 * 
 */
public class WelcomeActivity extends Activity implements OnViewLastListener {

	private MyScrollLayout myScroll;
	private Intent intent;
	private SharePreferenceUtil pefUtil;
	private Context context;
	private DBUtil dbUtil;
	private ProgressBar loading_pb;
	private final int GET_CITY_ERROR = 0x2220;
	private final int GET_CITY_SUCCESS = GET_CITY_ERROR + 1;
	private final int ENTER_HOME = GET_CITY_SUCCESS + 2;
	private final int LOCOCATION_SUCCESS = GET_CITY_SUCCESS + 3;

	private AMapLocation aMapLocation;// 用于判断定位超时
	private LocationManagerProxy aMapLocManager = null;
	private boolean isFirst = true;

	private LinearLayout splash_ll;
	private ImageView splash_des;
	private ImageView splash_logo;

	private City city;

	private LocationClient locationClient;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(receiver, filter);
		locationClient = ((GsooApplication) getApplication()).mLocationClient;
		dbUtil = DBUtil.newInstance(this);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		context = this;
		setContentView(R.layout.activity_welcome);
		loading_pb = (ProgressBar) findViewById(R.id.loading_pb);
		myScroll = (MyScrollLayout) findViewById(R.id.myScroll);
		pefUtil = new SharePreferenceUtil(this, "setting");
		isFirst = pefUtil.loadBooleanSharedPreference("isFirst", true);
		aMapLocManager = LocationManagerProxy.getInstance(this);
		splash_ll = (LinearLayout) findViewById(R.id.splash_ll);
		splash_des = (ImageView) findViewById(R.id.splash_des);
		splash_logo = (ImageView) findViewById(R.id.splash_logo);
		city = (City) pefUtil.loadObject("city");

		GsooApplication.lat = null;
		GsooApplication.lng = null;
		GsooApplication.cityName = null;

	}

	@Override
	protected void onResume() {
		super.onResume();
		GsooApplication.isShowTipChangeCity = true;
		GsooApplication.reset();
		int state = NetWorkHelper.getNetworkState(this);
		if (state == NetWorkHelper.NONE) {
			DialogUtil.createCallLoginDialog(this, "暂无网络连接",
					new DialogCallBack() {

						@Override
						public void viewClick() {
						}

						@Override
						public void ok() {
							if (android.os.Build.VERSION.SDK_INT > 10) {
								intent = new Intent(
										android.provider.Settings.ACTION_WIRELESS_SETTINGS);
							} else {
								intent = new Intent();
								ComponentName component = new ComponentName(
										"com.android.settings",
										"com.android.settings.WirelessSettings");
								intent.setComponent(component);
								intent.setAction("android.intent.action.VIEW");
							}
							startActivity(intent);
						}

						@Override
						public void init(Object obj) {

						}

						@Override
						public void cancel() {
							finish();
						}
					}, "打开网络", "取消", keylistener);
		}

		if (isFirst) {
			myScroll.setOnViewLastListener(this);
		} else {
			splash_ll.setVisibility(View.VISIBLE);
			myScroll.setVisibility(View.GONE);
			doAnimInitData();
		}
	}

	/**
	 * 动画 初始化 数据
	 */
	private void doAnimInitData() {

		Animation animation = AnimationUtils.loadAnimation(this,
				R.anim.splash_translate);
		final Animation fadeAnimation = AnimationUtils.loadAnimation(this,
				R.anim.splash_fade);
		splash_logo.startAnimation(animation);
		animation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {

				splash_des.setImageResource(R.drawable.splash_des);
				splash_des.setVisibility(View.VISIBLE);
				splash_des.startAnimation(fadeAnimation);
			}
		});

		fadeAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				loading_pb.setVisibility(View.VISIBLE);
				initData();
			}
		});
	}

	@Override
	public void slideEnd() {
		splash_ll.setVisibility(View.VISIBLE);
		myScroll.setVisibility(View.GONE);
		doAnimInitData();
	}

	private void initData() {
		try {

			if (city != null) {
				locationClient.start();
				GsooApplication.currentCity = city;
				handler.sendEmptyMessage(ENTER_HOME);
			} else {
				obtainCityList();
			}
		} catch (Exception e) {
			Message msg = handler.obtainMessage();
			msg.what = GET_CITY_ERROR;
			handler.sendMessage(msg);
			LogUtil.d("wxf", e.toString());
		}
	}

	private int page = 1;
	private int rows = 2000;

	private void obtainCityList() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context, Urls.CITY_LIST + "page=" + page + "&rows="
									+ rows);
					LogUtil.d("wxf", "result=" + result);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = GET_CITY_ERROR;
						handler.sendMessage(msg);
					} else {
						List<Area> result_citys = CityJson
								.getCityListByJson(result);
						if (result_citys.size() > 0) {
							updateData(result_citys);
						}
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = GET_CITY_ERROR;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "e:" + e.toString());
				}
			}
		}).start();
	}

	/**
	 * 更新数据
	 */
	private void updateData(List<Area> result_citys) {
		List<City> tempCitys = new ArrayList<City>();
		for (Area area : result_citys) {
			City city = new City();
			city.setCityId(area.getId());
			city.setName(area.getAreaName());
			String pingying = area.getPinyin();
			if (pingying == null || pingying.length() == 0) {
				city.setIndex(CommonUtil.getPinYinHeadChar(area.getAreaName()));
			} else {
				city.setIndex((String.valueOf(pingying.charAt(0)))
						.toUpperCase());
			}
			tempCitys.add(city);
		}
		dbUtil.insertCityList(tempCitys);
		handler.sendEmptyMessage(GET_CITY_SUCCESS);
	}

	/**
	 * 定位
	 */
	private void requestLocation() {

		locationClient.start();
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {

			case GET_CITY_SUCCESS:
				requestLocation();
				break;
			case GET_CITY_ERROR:
				Toast.makeText(WelcomeActivity.this, "初始化数据失败!", 500).show();
				finish();
				break;
			case ENTER_HOME:
				pefUtil.saveSharedPreferences("isFirst", false);
				intent = new Intent(WelcomeActivity.this, MainTabActivity.class);
				startActivity(intent);
				// overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
				finish();
				break;
			case LOCOCATION_SUCCESS:
				City city = dbUtil
						.queryCityByCityName(GsooApplication.cityName);
				if (city != null) {
					GsooApplication.currentCity = city;
					pefUtil.saveObject(city, "city");
					pefUtil.saveSharedPreferences("isSameCity", true);
				}
				handler.sendEmptyMessage(ENTER_HOME);
				break;
			}

		};
	};

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			handler.sendEmptyMessage(LOCOCATION_SUCCESS);
		}
	};

	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	};

	OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				return true;
			} else {
				return false;
			}
		}
	};

}
